# -*- coding: utf-8 -*-
"""Definition of the link banner content type
"""

from zope.interface import implements
from zope.component import adapts

from Products.Archetypes import atapi
from Products.validation import V_REQUIRED

from Products.ATContentTypes.content import base
from Products.ATContentTypes.content import schemata


from Products.ATContentTypes.content import link
from shema.archetype.interfaces import Ilinkbanner
from shema.archetype.interfaces import IBannerProvider

from shema.archetype.config import PROJECTNAME

from shema.archetype import archetypeMessageFactory as _

linkbannerSchema = link.ATLinkSchema.copy() + atapi.Schema((

    # -*- Your Archetypes field definitions here ... -*-

    # By using the name 'image' we can have the image show up in preview
    # folder listings for free
    atapi.ImageField('image',
        required=True,
        languageIndependent=True,
        storage=atapi.AnnotationStorage(),
        swallowResizeExceptions=True,
        max_size='no',
        sizes={'large'   : (768, 768),
               'preview' : (400, 400),
               'mini'    : (200, 200),
               'thumb'   : (128, 128),
               'tile'    :  (64, 64),
               'icon'    :  (32, 32),
               'listing' :  (16, 16),
               },
        validators=(('isNonEmptyFile', V_REQUIRED),
                    ('checkImageMaxSize', V_REQUIRED),),
        widget=atapi.ImageWidget(label= _(u"Imagem do Banner"),
                                 description = _(u"Adicione arquivo com a imagem para o banner"),
                                 show_content_type = False,),
        ),
        
    atapi.BooleanField('abrirJanela',
        storage=atapi.AnnotationStorage(),
        widget=atapi.BooleanWidget(label=_(u"Abrir em outra janela"),
                                  description=_(u"Marque se quiser que a página seja aberta em outra janela"))
        ),
        

))


# Set storage on fields copied from ATContentTypeSchema, making sure
# they work well with the python bridge properties.

linkbannerSchema['title'].storage = atapi.AnnotationStorage()
linkbannerSchema['description'].storage = atapi.AnnotationStorage()

schemata.finalizeATCTSchema(linkbannerSchema, moveDiscussion=False)


class linkbanner(link.ATLink):
    """um link com banner"""
    implements(Ilinkbanner)

    meta_type = "link banner"
    _at_rename_after_creation = True
    archetype_name = 'Link Banner'    
    schema = linkbannerSchema

    title = atapi.ATFieldProperty('title')
    description = atapi.ATFieldProperty('description')
    image = atapi.ATFieldProperty('image')
    abrirJanela = atapi.ATFieldProperty('abrirJanela')    

    # -*- Your ATSchema to Python Property Bridges Here ... -*-
    def tag(self, **kwargs):
        """Generate image tag using the api of the ImageField
        """
        return self.getField('image').tag(self, **kwargs)

    def __bobo_traverse__(self, REQUEST, name):
        """Give transparent access to image scales. This hooks into the
        low-level traversal machinery, checking to see if we are trying to
        traverse to /path/to/object/image_<scalename>, and if so, returns
        the appropriate image content.
        """
        if name.startswith('image'):
            field = self.getField('image')
            image = None
            if name == 'image':
                image = field.getScale(self)
            else:
                scalename = name[len('image_'):]
                if scalename in field.getAvailableSizes(self):
                    image = field.getScale(self, scale=scalename)
            if image is not None and not isinstance(image, basestring):
                # image might be None or '' for empty images
                return image

        return super(linkbanner, self).__bobo_traverse__(REQUEST, name)
    

atapi.registerType(linkbanner, PROJECTNAME)

class BannerProvider(object):
    implements(IBannerProvider)
    adapts(linkbanner)
    
    def __init__(self, context):
        self.context = context
    
    @property
    def tag(self):
        return self.context.getField('image').tag(self.context, scale='mini')
